/**
 * 帖子列表页
 */

import React, { Component } from 'react';
import {
  StyleSheet,
  Text,
  View,
  FlatList,
  TouchableHighlight,
  TouchableOpacity,
  TouchableWithoutFeedback,
  Image,
  Dimensions,
  Modal,
  ScrollView,
  PanResponder,
  PixelRatio,
} from 'react-native';

import Toast from 'react-native-root-toast';
import Icon from 'react-native-vector-icons/MaterialCommunityIcons';
import Config from '../common/config';
import Request from '../common/request';

let width = Dimensions.get('window').width;//获取视口宽度
let height = Dimensions.get('window').height;

class Topic extends React.Component {
  static navigationOptions = ({navigation}) => ({
    headerTitle: `【${navigation.state.params.name}】 版块`,
    // headerLeft: (
    //   <TouchableOpacity onPress={() => {navigation.pop()}}>
    //     <Text>返回</Text>
    //   </TouchableOpacity>
    // ),
    headerRight: (
      <TouchableOpacity onPress={() => {navigation.navigate("TopicEdit", {fid: navigation.state.params.id})}} style={styles.btnEditBox}>
        <Text style={styles.btnEditText}>发帖</Text>
        {/* <Icon name="plus" size={24} color="blue" /> */}
      </TouchableOpacity>
    )
  })
  constructor(props) {
    super(props);
    this.state = {
      fid: null,
      page: 1,//下一次请求的页码
      pagination: null,
      loading: false,
      refreshing: false,
      data: [],
      modalVisible: false,
      modalImages: [
        {uri: "http://huanbao.xiaomlove.com/storage/image/201708/kXfVF9ebSacFNCCOYVcFg8HGgw6fAZXKL3sZHvH9.jpeg"}
      ],
      currentModalImageIndex: 0,
      panResponder: {},
      pressStartX: null,
      pressStartY: null,
      pressStartTimestamp: null,
      prevPressStopTimestamp: null,
    };
  }

  componentWillMount() {
    this.state.panResponder = PanResponder.create({
      // 要求成为响应者：
      onStartShouldSetPanResponder: (evt, gestureState) => true,
      onStartShouldSetPanResponderCapture: (evt, gestureState) => true,
      onMoveShouldSetPanResponder: (evt, gestureState) => true,
      onMoveShouldSetPanResponderCapture: (evt, gestureState) => true,

      onPanResponderGrant: (evt, gestureState) => {
        // 开始手势操作。给用户一些视觉反馈，让他们知道发生了什么事情！

        // gestureState.{x,y} 现在会被设置为0
        //console.log("onPanResponderGrant: ", gestureState);
        this.setState({
          pressStartX: gestureState.x0,
          pressStartY: gestureState.y0,
          pressStartTimestamp: evt.nativeEvent.timestamp,
        });
        this.doOtherAction = false;
      },
      onPanResponderMove: (evt, gestureState) => {
        // 最近一次的移动距离为gestureState.move{X,Y}
        // 从成为响应者开始时的累计手势移动距离为gestureState.d{x,y}
        console.log("onPanResponderMove: ", gestureState.dx, gestureState.dy);
        Toast.show(gestureState.dx + "--" + gestureState.dy);
        (Math.abs(gestureState.dx) > 3 || Math.abs(gestureState.dy) > 3) && (this.doOtherAction = true);
      },
      onPanResponderTerminationRequest: (evt, gestureState) => true,
      onPanResponderRelease: (evt, gestureState) => {
        // 用户放开了所有的触摸点，且此时视图已经成为了响应者。
        // 一般来说这意味着一个手势操作已经成功完成。
        //console.log("onPanResponderRelease: ", gestureState);
        let x = evt.nativeEvent.pageX - this.state.pressStartX, 
        y = evt.nativeEvent.pageY - this.state.pressStartY,
        currentTime = evt.nativeEvent.timestamp,
        duration = currentTime - this.state.pressStartTimestamp;
        //console.log(x, y, time, evt.nativeEvent.locationX, evt.nativeEvent.locationY);
        this.setState({
          prevPressStopTimestamp: currentTime
        })
        
        this.timer && clearTimeout(this.timer);
        if (this.state.prevPressStopTimestamp && (currentTime - this.state.prevPressStopTimestamp < 200)) {
          //首先看是否双击，若是，执行双击动作
          console.log("onPanResponderRelease double press");
        } else if (!this.doOtherAction) {
          //没有其他动作且不满足双击重新设置定时器
          this.timer = setTimeout(() => {
            console.log("onPanResponderRelease 0.5秒后自动隐藏并清理");
            this.setState({modalVisible: false});
            clearTimeout(this.timer);
          }, 300);
        }

        if (this.state.prevPressStopTimestamp) {
          console.log("onPanResponderRelease 双击间隔时间: ", currentTime - this.state.prevPressStopTimestamp);
        }
        
      },
      onPanResponderTerminate: (evt, gestureState) => {
        // 另一个组件已经成为了新的响应者，所以当前手势将被取消。
        console.log("onPanResponderTerminate: ", gestureState);
      },
      onShouldBlockNativeResponder: (evt, gestureState) => {
        // 返回一个布尔值，决定当前组件是否应该阻止原生组件成为JS响应者
        // 默认返回true。目前暂时只支持android。
        return true;
      },
    });
  }


  componentDidMount() {
    this.setState({
      refreshing: true,
      fid: this.props.navigation.state.params.id
    }, () => {
      this.fetchTopics();
      console.log(width, height);
    });
  }

  componentWillUnmount() {
    this.timer && clearTimeout(this.timer);
  }

  editTopicBtn() {
    return (
      <TouchableOpacity>
        <Text>发帖</Text>
      </TouchableOpacity>
    )
  }

  fetchTopics() {
    var self = this;
    Request.get(Config.api.topic, "fid=" + self.state.fid + "&page=" + self.state.page)
    .then((response) => {
      console.log(response);
      self.setState({
        refreshing: false,
        loading: false,
      });
      if (response.ret == 0) {
        if (response.data.pagination.current_page == 1) {
          var newData = response.data.list;
        } else {
          var newData = [...self.state.data, ...response.data.list];
        }
        self.setState({
          data: newData,
          pagination: response.data.pagination,
          page: response.data.pagination.current_page + 1,
        });
      } else {
        AlertIOS.alert(response.msg);
      }
      
    })
  }

  renderItemSeparator() {
    return <View style={{width: "100%", height: 1, backgroundColor: "#ddd", marginTop: 20, marginBottom: 20}}/>
  }

  onRefresh() {
    if (this.state.loading) {
      return;
    }
    this.setState({
      page: 1,
      refreshing: true,
      loading: true,
    }, () => this.fetchTopics())
  }

  onEndReached() {
    if (this.state.page > this.state.pagination.total_pages) {
      return;
    }
    this.fetchTopics();
  }

  onItemPress(item) {
    this.props.navigation.navigate("Comment", {...item.item});
  }

  showPreviewImage(index, images) {
    console.log("showPreviewImage: ", index);
    this.setState({
      modalImages: images,
      currentModalImageIndex: index,
      modalVisible: true,
      prevPressStartTimestamp: null,
    }, () => {
      setTimeout(() => {
        this.refs.scrollView.scrollTo({
          x: index * width
        })
      }, 0)
    });
    
  }

  hidePreviewImageOnPressIn() {
    console.log("hidePreviewImageOnPressIn...");
    //this.setState({modalVisible: false});
  }
  hidePreviewImageOnPress() {
    console.log("hidePreviewImageOnPress...");
    //this.setState({modalVisible: false});
  }
   hidePreviewImageOnPressOut() {
    console.log("hidePreviewImageOnPressOut...");
    //this.setState({modalVisible: false});
  }

  hidePreviewImageByScrollView() {
    console.log("hidePreviewImageByScrollView press...");
    //this.setState({modalVisible: false});
  }
  
  renderItem(item, index) {
    //console.log(item);
    let self = this;
    return (
      <TouchableHighlight 
        style={styles.item} 
        onPress={() => self.onItemPress(item)}
        underlayColor="#ddd"
        activeOpacity={1}
      >
        <View >
          <View style={styles.itemHeader}>
            <Image style={styles.avatar} source={require('../asset/image/avatar.jpg')} />
            <View style={styles.nicknameBox}>
              <Text style={styles.nickname}>{item.item.user.data.name}</Text>
              <Text style={styles.lastCommentTime}>{item.item.last_comment_time_human}</Text>
            </View>
          </View>
          <View style={styles.itemContent}>
            <Text style={styles.title}>{item.item.title}</Text>
            <Text style={styles.excerpt}>{item.item.main_floor.data.detail.data.content}</Text>
            {
              item.item.main_floor.data.attachments && item.item.main_floor.data.attachments.data ?
              <View style={styles.images}>
                {
                  item.item.main_floor.data.attachments.data.map((elem, i, elems) => {
                    return (
                      <TouchableHighlight style={styles.imageWrap} onPress={() => self.showPreviewImage(i, elems)} key={elem.key}>
                        <Image style={styles.imagesItem} source={{uri: elem.uri}} />
                      </TouchableHighlight>
                    )
                  })
                }
              </View>
              :
              null
            }
          </View>
          <View style={styles.itemFooter}>
            <View style={styles.handleBox}>
              <Text style={styles.comment_count}>{item.item.comment_count}</Text>
              <Icon name="comment" style={styles.comment_count_icon} />
            </View>
            <View style={styles.handleBox}>
              <Text style={styles.view_count}>{item.item.view_count}</Text>
              <Icon name="view-list" style={styles.view_count_icon} />
            </View>
          </View>
        </View>
      </TouchableHighlight>
    );
  }

  renderModalImages() {
    var self = this;
   let items = [];
   this.state.modalImages.map((elem, i) => {
      items.push (
        <View 
          key={i} style={styles.modalImageWrap}         
        >
          <Image source={{uri: elem.uri}} style={styles.modalImage} {...self.state.panResponder.panHandlers} />
        </View>
      )
    });
    return items;
  }

  renderModalImagesPaginator() {
   let items = [];
   let count = this.state.modalImages.length;
   this.state.modalImages.map((elem, i) => {
      items.push (
        <Text key={i} style={[
          styles.paginationItem, 
          i == this.state.currentModalImageIndex ? {color: "orange"} : null,
          count == 1 ? {display: "none"} : null,
        ]}>.</Text>
      )
    });
    return items;
  }

  onModalImageScrollEnd(e) {
    var x = e.nativeEvent.contentOffset.x;
    console.log("onModalImageScrollEnd x: ", x);
    if (x == 0) {
      var index = 0;
    } else {
      var index = x / width;
    }
    this.setState({currentModalImageIndex: index});
  }

  render() {
    let Items = this.renderModalImages();
    let Paginator = this.renderModalImagesPaginator();
    return (
      <View style={styles.container}>
        <FlatList 
          style={styles.list}
          data={this.state.data}
          renderItem={(item, index) => this.renderItem(item, index)}
          ItemSeparatorComponent={this.renderItemSeparator}
          refreshing={this.state.refreshing}
          onRefresh={() => this.onRefresh()}
          onEndReached={() => this.onEndReached()}
          onEndReachedThreshold={0.2}
        />
        <Modal
          transparent={false}
          animationType={"none"}
          visible={this.state.modalVisible}
        >
          <ScrollView style={styles.scrollView}
            horizontal={true}
            pagingEnabled={true}
            onPress={() => this.hidePreviewImageByScrollView()}
            showsHorizontalScrollIndicator={false}
            showsVerticalScrollIndicator={false}
            onMomentumScrollEnd={(e) => this.onModalImageScrollEnd(e)}
            ref={"scrollView"}
            centerContent={true}
            onStartShouldSetResponder={(evt) => false}
          >   
          {Items} 
          </ScrollView>
          <View style={styles.paginationBox}>
            {Paginator}
          </View>
        </Modal>
      </View>
    );
  }
}

var styles = StyleSheet.create({
  container: {
    flex: 1,
  },

  list: {
    padding: 15,
  },
  item: {

  },
  itemHeader: {
    flex: 1,
    flexDirection: 'row',
  },
  nicknameBox: {
    flex: 1,
    justifyContent: 'center',
  },
  avatar: {
    width: 32,
    height: 32,
    marginRight: 8,
  },
  title: {
    fontSize: 18,
    fontWeight: "600",
    marginTop: 10,

  },
  excerpt: {
    marginTop: 10,
  },
  images: {
    display: 'flex',
    flexDirection: 'row',
    marginTop: 10,
  },
  imageWrap: {
    flex: 1
  },
  imagesItem: {
    flex: 1,
    height: 200,
    resizeMode: "cover"
  },
  itemFooter: {
    display: 'flex',
    flexDirection: 'row',
    justifyContent: 'flex-end',
    marginTop: 10,
  },
  handleBox: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    marginLeft: 10,
  },
  btnEditBox: {
    flexDirection: "row",
    justifyContent: "center",
    display: "flex",
    marginRight: 15,
  },
  btnEditText: {
    justifyContent: "center",
    textAlignVertical: "center",
    color: "green",
    paddingTop: 2,
    fontSize: 18
  },
  scrollView: {
    backgroundColor: "black",
  },
  modalImageWrap: {
    width: width,
    height: height,
  
  },
  modalImage: {
    width: width,
    resizeMode: "contain",
    flex: 1,
  },
  paginationBox: {
    width: width,
    height: 80,
    flexDirection: "row",
    position: "absolute",
    bottom: 40,
    alignItems: "center",
    justifyContent: "center",
    backgroundColor: "transparent"
  },
  paginationItem: {          
    fontSize: 80,
    color: "white",
  }

});

module.exports = Topic;

